<template>
  <div class="common-wrapper page-warning">
    <div class="common-title">告警设置</div>
    <div class="common-main">
      <el-form
        ref="search"
        class="common-search"
        :inline="true"
        :rules="searchRules"
        :model="search"
        :show-message="false"
      >
        <el-form-item>
          <el-select
            v-model="search.type"
            placeholder="选择数据源类型"
            size="small"
            clearable
          >
            <el-option
              v-for="(item, index) in orgOption"
              :key="index"
              :label="item['key_value']"
              :value="item['key_value']"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="search.name"
            placeholder="输入事件名称"
            size="small"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item class="btn-list">
          <el-button type="primary" size="small" @click="searchNow"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="bg-title mb10">
        <span class="select-count">已选中{{multipleSelection.length}}条记录</span>
        <el-divider direction="vertical" style="margin: 0 20px"></el-divider>
        <el-button type="text" icon="el-icon-circle-plus-outline" @click="onAdd"
          >新增</el-button
        >
        <!-- <el-button type="text" icon="el-icon-edit-outline" class="btn-color-g"
          >编辑</el-button
        > -->
        <el-button
          type="text"
          icon="el-icon-delete"
          class="btn-color-red"
          @click="onDelete"
          >删除</el-button
        >
        <!-- <el-divider direction="vertical"></el-divider>
        <el-button type="text" icon="el-icon-download">下载</el-button>
        <el-button type="text" icon="el-icon-upload2">导入</el-button> -->
        <el-divider direction="vertical"></el-divider>
        <el-button type="text" icon="el-icon-video-play" class="btn-color-g"
          @click="onActive('active')">上线</el-button
        >
        <el-button type="text" icon="el-icon-video-pause" class="btn-color-g"
         @click="onActive('offline')" >下线</el-button
        >
      </div>
      <div
        class="common-table"
        ref="chartTable"
        style="height: calc(100% - 150px)"
      >
        <el-table
          :data="tableData"
          @selection-change="selectionChange"
          style="width: 100%"
          :max-height="tableHeight"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="序号" width="55" align="center">
            <template slot-scope="{ row, column, $index }">
              {{ parseInt($index) + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" align="center" />
           <el-table-column prop="code" label="编号" align="center" />
          <el-table-column
            prop="ruleNumber"
            label="规则数量"
            align="center"
          />
          <el-table-column
            prop="createTime"
            label="添加时间"
            align="center"
          />

          <el-table-column prop="isActive" label="状态" align="center">
            <template slot-scope="{ row }">
               <el-tag
                size="mini"
                class="table-tag"
                :type="!row.isActive?'info':'warning'"
                >{{row.isActive ?'上线':'下线'}}</el-tag>
            </template>
          </el-table-column>
           <el-table-column prop="action" label="操作" width="120px" align="center">
             <template slot-scope="{ row }">
              <el-button
                type="text"
                icon="el-icon-edit-outline"
                @click="onEdit(row)"
                >编辑</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="common-pagination">
        <el-pagination
          background
          layout="prev, pager, next, sizes, jumper"
          :page-size="search.pageSize"
          :current-page.sync="search.pageNum"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getSysDict,
  getSysDictByName,
  getParams1,
  getParams2,
} from '@/api/common';
import { getAlarmConfigList ,apiAlarmConfig} from '@/api/alarm';
export default {
  data() {
    return {
      tableHeight: 200,
      multipleSelection: [],
      time: [],
      search: {
        org: '恒源',
        name: '',
        pageSize: 10,
        pageNum: 1,
      },
      searchRules: {
        params: [
          { required: true, message: '请选择参数！', trigger: 'change' },
        ],
        devSn: [{ required: true, message: '请选择车台！', trigger: 'change' }],
        startTime: [
          { required: true, message: '请选择时间！', trigger: 'change' },
        ],
      },
      cascaderProps: {
        lazy: true,
        multiple: true,
        label: 'label',
        lazyLoad: async (node, resolve) => {
          if (node.level) {
            let form = {
              gongxu: node.data.gongxu,
              cs_type: node.data.cs_type,
            };
            const { data } = await getParams2(form);
            data.map((item) => {
              item.label = item['cs_name'];
              item.value = item['cs'];
              item.leaf = true;
            });
            resolve(data);
          }
        },
      },
      options: [],
      // 图表部分
      legend: [],
      series: [],
      yAxis: [],
      timeSource: [],
      total: 10,
      chartActive: '',
      chartBtnArr: [],
      myChart: null,
      loading: false,
      csOption: [],
      equipOption: [],
      tableData: [],
      columns: [],
    };
  },
  created() {
    window.addEventListener('resize', () => {
      this.getHeight();
      this.getTableData();
    });
  },
  mounted() {
    document.getElementsByClassName(
      'el-pagination__jump'
    )[0].childNodes[0].nodeValue = '跳至';
    this.$nextTick(() => {
      this.getHeight();
      this.getTableData();
      this.getParams();
    });
  },
  destroyed() {
    window.removeEventListener('resize', this.getHeight, this.getTableData);
  },
  computed: {
    bcOption() {
      return this.$store.getters.bcOption;
    },
    orgOption() {
      return this.$store.getters.orgOption;
    },
    cjOption() {
      return this.$store.getters.cjOption;
    },
    gxOption() {
      return this.$store.getters.gxOption;
    },
  },
  methods: {
    selectionChange(val) {
      this.multipleSelection = val;
    },
    onActive(cmd){
      let text = cmd == 'active'?'上线':'下线'
      if (this.multipleSelection.length == 0) {
        return this.$message.error(`请选择需要${text}的数据!`);
      }
      let ids = this.multipleSelection.map((item) => item.id);

      this.$confirm(`是否确认${text}告警配置吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        apiAlarmConfig(cmd,{
          idList:ids
        }).then((res) => {
          if (res.code == 1) {
            this.$message({
              message: `${text}成功`,
              iconClass: 'el-icon-success',
              customClass: 'common-message',
            });
            this.getTableData()
          }
        });
      });
    },
    onDelete() {
      if (this.multipleSelection.length == 0) {
        return this.$message.error('请选择需要删除的数据!');
      }
      let ids = this.multipleSelection.map((item) => item.id);

      this.$confirm('是否确认删除告警配置吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        apiAlarmConfig('delete',{
          array:ids
        }).then((res) => {
          if (res.code == 1) {
            this.$message({
              message: '删除成功',
              iconClass: 'el-icon-success',
              customClass: 'common-message',
            });
            this.getTableData()
          }
        });
      });
    },
    onEdit(data){
      this.$router.push({
        path: '/SystemtionAdd',
        query:{
          id:data.id
        }
      });
    },
    onAdd() {
      this.$router.push({
        path: '/SystemtionAdd',
      });
    },
    // 下拉框部分
    async getParams(val) {
      const { data } = await getParams1({ gongxu: val });
      let arr = [];
      data.map((item) => {
        let obj = Object.assign({}, item);
        obj.label = item.cs_type;
        obj.value = item.cs_type;
        arr.push(obj);
      });
      this.options = arr;
    },
    async getEquip(val) {
      const equipData = await getSysDict(val);
      this.equipOption = equipData.data.dataList;
    },
    async getTableData() {
      let form = Object.assign({}, this.search);
      delete form['params'];
      const res = await getAlarmConfigList(form);
      if (res.code == 1) {
        this.tableData = res.data.dataList;
        this.total = res.data.total;
      }
    },

    getHeight() {
      this.tableHeight = this.$refs.chartTable.offsetHeight;
    },
    handleSizeChange(val) {
      this.search.pageNum = 1;
      this.search.pageSize = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.search.pageNum = val;
      this.getTableData();
    },
    searchNow() {
      this.$refs['search'].validate((valid, object) => {
        this.getTableData();
      });
    },
    groupBy(array, f) {
      let groups = {};
      array.forEach(function (o) {
        var group = JSON.stringify(f(o));
        groups[group] = groups[group] || [];
        groups[group].push(o);
      });
      return Object.keys(groups).map(function (group) {
        return groups[group];
      });
    },
    arrayGroupBy(list, groupId) {
      let sorted = this.groupBy(list, function (item) {
        return [item[groupId]];
      });
      return sorted;
    },
    llxsFilter(row, col, val) {
      return parseInt(val) / 100;
    },
  },
};
</script>

<style lang="scss" scoped>
.common-wrapper {
  height: 100%;
}

.common-search {
  display: flex;

  ::v-deep .btn-list .el-form-item__content {
    display: flex;
  }
}
.page-warning {
  .bg-title {
    background: #f6f9fc;
    box-sizing: border-box;
    padding: 6px 15px;
    .select-count {
      font-size: 15px;
      color: #9ea2ba;
    }
    .el-divider.el-divider--vertical {
      margin: 0 20px;
    }
    .btn-color-g {
      color: #9ea2ba;
    }
    .btn-color-red{
      color: #f56c6c;
    }
  }
}
</style>
